package com.majun.utils;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Map;


/**
 * SpringContext工具类
 * @author majun
 * @date 2025/04/16
 */
@Component
public class SpringContextUtil implements ApplicationContextAware {
    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContextUtil.applicationContext = applicationContext;
    }

    /**
     * 获取ApplicationContext
     *
     * @return org.springframework.context.ApplicationContext
     * @author xuhao
     * @create 2021/3/29 16:48
     */
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    /**
     * 根据beanName获取spring容器中对象
     *
     * @param beanName
     * @return T
     * @author xuhao
     * @create 2021/3/29 16:49
     */
    @SuppressWarnings("unchecked")
    public static <T> T getBean(String beanName) throws BeansException {
        return (T) applicationContext.getBean(beanName);
    }

    /**
     * 根据beanName获取spring容器中对象
     *
     * @param beanName
     * @return T
     * @author xuhao
     * @create 2021/3/29 16:49
     */
    @SuppressWarnings("unchecked")
    public static <T> T getBeansOfType(Class<T> clazz) throws BeansException {
        Map<String, T> beansOfType = applicationContext.getBeansOfType(clazz);
        String name = clazz.getName();
        String substring = name.substring(name.lastIndexOf(".") + 1);
        String head = substring.substring(0, 1);
        String body = substring.substring(1);
        return beansOfType.get(head.toLowerCase() + body);

    }




}

